package org.yuezejian.alarm.netty.channel.pool;

import org.yuezejian.alarm.netty.channel.TCPCustomChannelInitializer;
import org.yuezejian.alarm.netty.channel.UDPCustomChannelInitializer;
import org.yuezejian.alarm.netty.channel.WebsocketCustomChannelInitializer;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 通道池，用于管理和分配netty通道
 *
 * @author yuezejian
 * @since 2024.8.1
 */
public abstract class AbstractChannelPool {
    protected final ConcurrentLinkedQueue<Channel> pool = new ConcurrentLinkedQueue<>();
    protected final EventLoopGroup group = new NioEventLoopGroup();
    protected final String host;
    protected final int port;
    protected final TCPCustomChannelInitializer tcpInitializer;
    protected final UDPCustomChannelInitializer udpInitializer;
    protected final WebsocketCustomChannelInitializer wsInitializer;

    public AbstractChannelPool(String host, int port, TCPCustomChannelInitializer tcpInitializer, UDPCustomChannelInitializer udpInitializer, WebsocketCustomChannelInitializer initializer) {
        this.host = host;
        this.port = port;
        this.tcpInitializer = tcpInitializer;
        this.udpInitializer = udpInitializer;
        this.wsInitializer = initializer;
    }

    public Channel acquireChannel() throws InterruptedException {
        Channel channel = pool.poll();
        if (channel == null || !channel.isActive()) {
            channel = createNewChannel();
        }
        return channel;
    }

    protected abstract Channel createNewChannel() throws InterruptedException;

    public void releaseChannel(Channel channel) {
        if (channel.isOpen()) {
            pool.offer(channel); // 将通道返回到池中
        } else {
            // 处理已关闭的通道，可能记录日志或清理
        }
    }

    public void shutdown() {
        group.shutdownGracefully(); // 优雅关闭 EventLoopGroup
    }
}
